class PresentableController < ApplicationController
	after_filter :update_user_groups, :only => [:create, :update]

	private

	def update_user_groups 
		#
		# All security is managed through the associated content (aka presentable)
		#
		secure_model = user_group_security_model_instance.content
		new_user_group_ids = params.collect{|p| p[0].split("_")[1].to_i if p[0] =~ /^grp_/}.compact
		#
		# Removed previously associated user_groups if not checked this time.
		#
		secure_model.user_groups.dup.each do |ug|
			unless new_user_group_ids.include?(ug.id)
				secure_model.user_groups.delete(ug) 
			end
		end
		# 
		# Add in the new user_groups
		#
		new_user_group_ids.each do |id|
			next if secure_model.user_group_ids.include?(id)
			secure_model.user_groups << UserGroup.find(id)
		end
	end

	def user_group_security_model_instance
		instance_variable_get("@#{controller_model_name}")
	end

	def controller_model_name
		self.controller_name.singularize
	end

	def controller_model_class_name
		self.controller_name.singularize.camelize
	end

end